// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  let {
    bookId,
    userId,
    remaining
  } = event
  // 在用户表中的borrowed添加书籍id
  db.collection('userInfo').doc(userId).update({
    data: {
      borrowed: _.push(bookId)
    }
  })

  // 用户表中的integral加1
  let {data} = await db.collection('userInfo').doc(userId).get()
  integral = data.integral
  integral += 1


  db.collection('userInfo').doc(userId).update({
    data:{
      integral
    }
  })

  remaining -= 1

  // bookItem中的remaing减少
  db.collection('bookItem').where({
    id: bookId
  }).update({
    data: {
      remaining
    }
  })


}